<?php

class Core_Backend_Component_Foundation_Controller_Road extends Dcmp_Component_Controller {
	
    public function indexAction($pageindex = 1, $pagesize = 20) {
        $this->getHistory()->record();
        $validator = $this->getRequest()->getValidator('filter');
        $collection = App::getModel('foundation/collection_road')->pagination($pageindex, $pagesize);
        if(!$this->getIdentity()->isInRole('resource_manager')){
        	$collection->innerJoin('{t}account_road', 'z', 'z.road_id', 'a.id')
        			   ->eq('z.account_id', $this->getIdentity()->getId());
        }        
		if($validator->isNotEmpty('province_name')){
			$collection->filterByProvinceName($validator->getValue('province_name'));
		}
    	if($validator->isNotEmpty('city_name')){
			$collection->filterByCityName($validator->getValue('city_name'));
		}
    	if($validator->isNotEmpty('townstreet_name')){
			$collection->filterByTownstreetName($validator->getValue('townstreet_name'));
		}
    	if($validator->isNotEmpty('road_name')){
			$collection->filterByRoadName($validator->getValue('road_name'));
		}
        if($validator->isNotEmpty('district_name')){
			$collection->filterByDistrictName($validator->getValue('district_name'));
		}
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function assignPostAction() {
    	$roads = App::getModel('foundation/collection_road')
    				->contain('a.id', ':roadIds:s')
    				->addParameter('roadIds', $this->getRequest()->getForm('ids'))
    				->load();
		$accounts = App::getModel('permission/collection_account')->load();
		$selectedAccounts = Kd_Data_Factory::getQueryDcl()
		        	->from('{t}foundation_road_account')
					->contain('road_id', ':roadIds:s')
					->addParameter('roadIds', $this->getRequest()->getForm('ids'))
					->field('account_id')
					->distinct()
					->fetch()
					->getFieldValues('account_id');
		return $this->viewResult(array('accounts'=>$accounts, 'account_ids'=>$selectedAccounts, 'roads'=>$roads));
    }

    public function saveAssignPostAction(){
		$roadIds = $this->getRequest()->getForm('road_ids');
		$accountIds = $this->getRequest()->getForm('account_ids');
		Kd_Data_Factory::getDeleteDcl()
			->from('{t}foundation_road_account')
			->where()->contain('road_id', ':roadIds:s')->closest()
			->addParameter('roadIds', $roadIds)
			->execute();

		$sql = Kd_Data_Factory::getInsertDcl()
				->into('{t}foundation_road_account')
				->value('road_id', ':roadId:s')
				->value('account_id', ':accountId:i')
				->toSql();
		$driver = Kd_Db_Factory::getDriver();
		foreach($accountIds as $accountId){
			foreach($roadIds as $roadId){
				$driver->setSql($sql, array('roadId'=>$roadId, 'accountId'=>$accountId))->execute();
			}
		}
		return $this->redirectResult($this->getHistoryUrl('foundation/road/index'));
    }
}